package top.foxhome.productimages.productimages;

import java.io.*;
import java.util.Properties;

/**
 * 数据保持类
 */
public class ConfigProperties {
    private final Properties mProperties;
    private final static String CONFIG_NAME = "./config";
    private static ConfigProperties instance;
    public static final String CONFIG_KEY_WORK_DIRECTORY = "workdirectory";

    public static ConfigProperties getInstance() {
        if (instance == null) instance = new ConfigProperties();
        return instance;
    }

    private ConfigProperties() {
        File mFile = new File(CONFIG_NAME);
        mProperties = new Properties();
        if (mFile.exists()) {
            try {
                InputStream inputStream = new FileInputStream(CONFIG_NAME);
                mProperties.loadFromXML(inputStream);
                mProperties.list(System.out);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getValue(String key) {
        return getValue(key, "");
    }

    public String getValue(String key, String defaultValue) {
        String value = mProperties.getProperty(key);
        return value == null ? defaultValue : value;
    }

    public void setValue(String key, String value) {
        mProperties.setProperty(key, value);
    }

    public void save() {
        try {
            PrintStream fW = new PrintStream(new File(CONFIG_NAME));
            mProperties.storeToXML(fW, "test");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
